import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Tree, Icon, Skeleton, Modal, Tag } from 'antd';
import ScrollBar from '@/components/ScrollBar';
import request from '@/utils/request';
import styles from '../index.less';
import Ikon from '@/components/Ikon';

const { TreeNode } = Tree;
const { CheckableTag } = Tag;

function SetCondition({ size, visiable, close, status }) {
  // 组织树数据
  const [TreeData, setTreeData] = useState([]);
  // 选中点击的值
  const [selectedKeysArr, setSelectedKeysArr] = useState(['']);
  // 初始化加载组织树loading
  const [loading, setLoading] = useState(false);
  // 设置条件属性值展示
  const [attributeValue, setAttributeValue] = useState([]);
  const [attrValLoading, setAttrValLoading] = useState(false);
  // 设置条件属性值展示选择项
  const [selectedTags, setSelectedTags] = useState([]);

  // 初始化获取接口的Tree集合
  const queryTreeData = () => {
    setLoading(true);
    request('/oc/RuleCfgController/showCondTree.do', {
      method: 'POST',
    })
      .then(res => {
        if (res.tree_list.length > 0) {
          setTreeData(res.tree_list);
        }
      })
      .always(() => setLoading(false));
  };

  useEffect(() => {
    queryTreeData();
  }, []);

  // 遍历递归集合数据，渲染组织树
  const renderTreeNode = TreeArr => {
    if (TreeArr.length > 0) {
      return TreeArr.map(item => {
        return (
          <TreeNode
            icon={({ expanded }) => (
              /* eslint-disable */
              <Icon
                type={
                  expanded
                    ? item.children && item.children.length > 0
                      ? 'folder-open'
                      : 'file'
                    : item.children && item.children.length > 0
                    ? 'folder'
                    : 'file'
                }
              />
              /* eslint-enable */
            )}
            title={item.name}
            key={`${item.id},${item.data ? item.data.stypeCode : undefined}`}
            isLeaf={item.children && item.children.length > 0 ? false : true}
            // 往组织树挂一个detaRef 可供外部获取选中的整个对象数据
            dataRef={item}
          >
            {item.children ? renderTreeNode(item.children) : null}
          </TreeNode>
        );
      });
    }
  };

  // 选中节点
  const selectTreeNode = selectedKeys => {
    /* eslint-disable */
    selectedKeys.length > 0
      ? setSelectedKeysArr(selectedKeys)
      : setSelectedKeysArr(selectedKeysArr);

    let typeCode = '';
    if (selectedKeys.length > 0) {
      typeCode = selectedKeys.toString().match(/,(\S*)/)[1];
    } else {
      typeCode = selectedKeysArr.toString().match(/,(\S*)/)[1];
    }
    /* eslint-enable */

    if (typeCode !== 'undefined') {
      setAttrValLoading(true);
      request('/oc/StaticDataController/getStaticAttr.do', {
        data: typeCode,
      })
        .then(res => {
          setAttributeValue(res);
        })
        .always(() => {
          setAttrValLoading(false);
        });
    } else {
      setAttributeValue([]);
    }
  };

  const handleChange = (tag, checked) => {
    const nextSelectedTags = checked ? [...selectedTags, tag] : selectedTags.filter(t => t !== tag);
    setSelectedTags(nextSelectedTags);
  };

  return (
    <Modal
      title={status === 'set' ? '设置条件' : '规则结果'}
      width="800px"
      destroyOnClose
      visible={visiable}
      okText="保存"
      onOk={close}
      onCancel={close}
    >
      <div className={styles.scroll_main}>
        <div className={styles.scroll_left}>
          <ScrollBar autoHide autoHeight autoHeightMax={size.height * 0.7}>
            <div style={{ height: size.height * 0.7, paddingRight: '8px' }}>
              <Skeleton active loading={loading}>
                {TreeData.length > 0 ? (
                  <Tree
                    showIcon
                    onSelect={selectTreeNode}
                    selectedKeys={selectedKeysArr}
                    defaultExpandAll
                  >
                    {renderTreeNode(TreeData)}
                  </Tree>
                ) : null}
              </Skeleton>
            </div>
          </ScrollBar>
        </div>
        <div
          className={styles.scroll_content}
          style={{ paddingLeft: '16px', borderLeft: '1px solid #e8e8e8' }}
        >
          <ScrollBar autoHide autoHeight autoHeightMax={size.height * 0.7}>
            <div style={{ height: size.height * 0.7 }} className={styles.set_conditionright}>
              <div className="ant-detail-title">属性值展示</div>
              {/* <Ikon status="404" subTitle="请选取对应的子节点获取属性值展示" /> */}
              {attributeValue.length > 0 ? (
                <Skeleton active loading={attrValLoading}>
                  <div className={styles.radio}>
                    {attributeValue.map(tag => (
                      <CheckableTag
                        key={tag.attrId}
                        checked={selectedTags.indexOf(tag.attrId) > -1}
                        onChange={checked => handleChange(tag.attrId, checked)}
                      >
                        {tag.attrValueName}
                      </CheckableTag>
                    ))}
                  </div>
                </Skeleton>
              ) : (
                <Ikon status="404" subTitle="抱歉，暂无属性值展示 ~" />
              )}
            </div>
          </ScrollBar>
        </div>
      </div>
    </Modal>
  );
}

export default connect(({ setting }) => ({
  size: setting.size,
}))(SetCondition);
